﻿using System;
using Model;
using Model.Entities;
using MusicSite.ViewClasses;

namespace MusicSite.Views.Content.User
{
    public partial class EditUser : BasePage
    {
        private UserProvider usProv = new UserProvider();
        private UserDetails user = new UserDetails();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckAuthenticationEditPage();
            string userId = Request.QueryString["UserId"];
            if (string.IsNullOrEmpty(userId))
            {
                btnDelete.Visible = false;
                btnUpdate.Text = "Create";
                return;
            }
            user = usProv.GetUserById(Convert.ToInt32(userId));
            if (!IsPostBack)
            {
                userName.Text = user.UserName;
                pass.Text = user.Password;
                userRole.SelectedItem.Value = user.UserRole.ToString();
            }
        }

        protected void UpdateUser(object sender, EventArgs e)
        {
            if (IsValid)
            {
                user.UserName = userName.Text;
                user.Password = pass.Text;
                user.UserRole = (UserRole) Enum.Parse(typeof(UserRole), userRole.SelectedValue);
                if (btnUpdate.Text == "Create")
                    usProv.InsertUser(user);
                else
                    usProv.UpdateUser(user);
                Response.Redirect("~/Views/Content/User/AdminPage.aspx");
            }
        }

        protected void DeleteUser(object sender, EventArgs e)
        {
            usProv.DeleteUser(user.UserId);
            Response.Redirect("~/Views/Content/User/AdminPage.aspx");
        }
    }
}
